<template>
  <div class="tax-bar-chart">
    <div ref="chartRef" style="width: 100%; height: 215px"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts/core'
import { BarChart } from 'echarts/charts'
import {
  TooltipComponent,
  GridComponent,
  TitleComponent,
  LegendComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import type { ECharts } from 'echarts/core'

// 注册需要的组件
echarts.use([
  BarChart,
  TooltipComponent,
  GridComponent,
  TitleComponent,
  LegendComponent,
  CanvasRenderer
])

const chartRef = ref<HTMLDivElement | null>(null)
let myChart: ECharts | null = null

// 父组件传参
const { data } = defineProps<{
  data: { name: string; value: number }[]
}>()

// 图表响应式刷新
watch(
  () => data,
  () => {
    if (myChart) {
      myChart.setOption(getOption())
    }
  },
  { deep: true }
)

onMounted(() => {
  if (chartRef.value) {
    myChart = echarts.init(chartRef.value)
    myChart.setOption(getOption())
  }
  window.addEventListener('resize', resizeChart)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeChart)
  myChart?.dispose()
})

function resizeChart() {
  myChart?.resize()
}

// 图表配置
function getOption() {
  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      top:30,
      left: 10,
      right: 0,
      bottom: 0,
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.map(item => item.name),
      axisLine: {
        lineStyle: {
          color: '#ccc'
        }
      },
      axisLabel: {
        color: '#4E718F'
      }
    },
    yAxis: {
      type: 'value',
      name: '单位：亿元',
      nameTextStyle: {
        padding:[0, 0, 0, 15], // 上右下左
        color: '#4E718F',
        fontSize: 12,
      },
      axisLine: {
        lineStyle: {
          color: '#ccc'
        }
      },
      splitLine: {
        lineStyle: {
          color: '#e0e6f1'
        }
      },
      axisLabel: {
        color: '#4E718F'
      }
    },
    series: [
      {
        name: '重点免税商品销售情况',
        type: 'bar',
        data: data.map(item => item.value),
        barWidth: 30,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(85,224,255,0.8)' },
            { offset: 1, color: 'rgba(53,101,222,0.08)' }
          ])
        },
        label: {
          show: true,
          position: 'top',
          color: '#4E718F',
          fontSize: 12
        }
      }
    ]
  }
}
</script>

<style lang="less" scoped>
.tax-bar-chart {
  flex: 1;
}
</style>
